import Mock from 'mockjs';
import userMock from './user';

// 定义mock接口类型
interface MockItem {
  (options: any): any;
}

interface MockCollection {
  [key: string]: MockItem | any;
}

// Mock配置
const mockConfig = {
  // 是否启用Mock
  enabled: true,
  // 延迟响应时间（毫秒）
  timeout: 300,
};

// 合并所有mock数据
const mocks: MockCollection = {
  ...userMock,
};

// 注册mock拦截
function registerMock() {
  if (!mockConfig.enabled) {
    return;
  }

  Object.keys(mocks).forEach((key) => {
    const [method, url] = key.split(' ');
    
    Mock.mock(new RegExp(`^${url.replace(/\/:/g, '/[^/]+')}$`), method, (options: any) => {
      console.log(`[Mock] ${method} ${url}`);

      // 延迟响应
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockItem = mocks[key];
          const result = typeof mockItem === 'function' 
            ? mockItem({
                ...options,
                query: options.query,
                body: options.body,
                params: extractParams(url, options.url),
              })
            : mockItem;
          resolve(result);
        }, mockConfig.timeout);
      });
    });
  });
}

// 从URL中提取参数
function extractParams(pattern: string, url: string) {
  const params: Record<string, string> = {};
  const patternParts = pattern.split('/');
  const urlParts = url.split('/');
  
  patternParts.forEach((part, index) => {
    if (part.startsWith(':')) {
      const paramName = part.slice(1);
      params[paramName] = urlParts[index];
    }
  });
  
  return params;
}

// 导出
if (mockConfig.enabled) {
  registerMock();
  console.log('[Mock] Mock数据已启用');
}

export default mocks;
export { mockConfig };